<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Ip extends Backend
{

    /**
     * Cate模型对象
     * @var \app\admin\model\Ip
     */
    protected $model = null;
    protected $noNeedLogin = ['getip'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Ip();

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function getip()
    {
        //$data = file_get_contents("http://pandavip.xiongmaodaili.com/xiongmao-web/apiPlus/vgl?secret=600b4144b732dcfd95fbcaafd8a9bb7f&orderNo=VGL20220601205250PVlA5w72&count=2&isTxt=0&proxyType=1&validTime=0&removal=0&cityIds=");

        $h = date('H');
        if ($h >= 8 && $h <= 12){
            $count = config("site.ip_count");
            $number = Db::name('ip')->count();

            $this->getstatus();

            log_print($number, $count);
            if ($number < $count) {
                $data = file_get_contents(config("site.ipurl"));
                $re_data = json_decode($data, true);
                log_print($data);
                $in_arr = [];
                if ($re_data['code'] == 0) {
                    foreach ($re_data['obj'] as $k => $v) {
                        $in_arr[$k]['content'] = $v['ip'] . ":" . $v['port'];
                        $in_arr[$k]['create_time'] = time();
                    }
                }

                $this->model->insertAll($in_arr);
            }

            $this->getstatus();
        }
    }

    /**
     * get 请求
     * @param $url
     * @param bool $is_proxy
     * @return mixed|string
     * @throws Exception
     */
    private function getstatus()
    {
        $info = $this->model->field('id,content')->select();
        foreach ($info as $v) {
            $this->check_ip($v['id'], $v['content']);
        }
        echo "succ";

    }

    private function check_ip($id, $proxy)
    {
        $url = 'https://hk.sz.gov.cn:8118/userPage/login';

        $arr = explode(':', $proxy);
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); //代理认证模式
        curl_setopt($ch, CURLOPT_PROXY, $arr[0]); //代理服务器地址
        curl_setopt($ch, CURLOPT_PROXYPORT, $arr[1]); //代理服务器端口
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); //使用http代理模式

        $error = curl_error($ch);
        $info = curl_exec($ch);

//        log_print($error, $info);

        if (!$info) {
            Db::name('ip')->where('id', $id)->delete();
        }

        curl_close($ch);
    }
}
